package com.xuzhijie.pms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.common.Result;
import com.xuzhijie.pms.entity.Renovation;
import com.xuzhijie.pms.entity.Repair;
import com.xuzhijie.pms.entity.vo.RenovationVo;
import com.xuzhijie.pms.entity.vo.RepairVo;
import com.xuzhijie.pms.exception.PmsServerException;
import com.xuzhijie.pms.mapper.RepairMapper;
import com.xuzhijie.pms.service.IRepairService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 许志杰
 * @since 2024-02-17
 */
@Service
public class RepairServiceImpl extends ServiceImpl<RepairMapper, Repair> implements IRepairService {

    @Override
    public Result findPage(Integer page, Integer size, Integer repairType, Integer repairProgress, Integer source) {
        Page<Repair> repairPagePage = new Page<>(page,size);
        QueryWrapper<Repair> queryWrapper = new QueryWrapper<>();
        Page<Repair> result;
        Long total;

        if (!repairType.equals(0)){
            queryWrapper.eq("repair_type",repairType);
        }

        if (!repairProgress.equals(0)){
            queryWrapper.eq("repair_progress",repairProgress);
        }

        if (!source.equals(0)){
            queryWrapper.eq("source",source);
        }


        try {
            result = page(repairPagePage,queryWrapper);
            total = count(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            throw new PmsServerException("业务繁忙", Constants.SYSTEM_ERROR);
        }

        List<Repair> repairList = result.getRecords();
        List<RepairVo> voList = new ArrayList<>();
        for (Repair repair : repairList) {
            RepairVo repairVo = new RepairVo(repair);
            BeanUtil.copyProperties(repair,repairVo);
            voList.add(repairVo);
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("records",voList);
        resultMap.put("total",total);

        return Result.success(resultMap);
    }

    @Override
    public Result addrepair(String description, String type, String phone, String images, String address) {
        Repair repair = new Repair();
        repair.setDescription(description);
        repair.setPhone(phone);
        repair.setRepairType(Integer.parseInt(type));
        repair.setImages(images);
        repair.setRepairLocation(address);
        repair.setSource(1);
        repair.setRepairProgress(1);
        save(repair);
        return Result.success();
    }
}
